package com.lingtao.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;

import com.blankj.utilcode.util.PathUtils;
import com.lingtao.myapplication.media.IjkVideoView;
import com.lingtao.myapplication.media.LogUtils;

import java.io.File;
import java.io.IOException;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;
import tv.danmaku.ijk.media.player.misc.ITrackInfo;

public class PlayVideoActivity extends AppCompatActivity implements View.OnClickListener {


    private IjkVideoView mVideoView;
    private Button recored;
    private Button screenshot;
    private ImageView fragme;


    public static void start(Context context) {
        Intent starter = new Intent(context, PlayVideoActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_video);


        mVideoView = findViewById(R.id.video_view);
        recored = findViewById(R.id.recored);
        screenshot = findViewById(R.id.screenshot);
        fragme = findViewById(R.id.fragme);

        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");
        mVideoView = (IjkVideoView) findViewById(R.id.video_view);
//        mVideoView.setHudView(mHudView);

        initVideoViewListener();
        startPlay();

        recored.setOnClickListener(this);
        screenshot.setOnClickListener(this);
    }

    private void startPlay() {
//        String path = "http://ips.ifeng.com/video19.ifeng.com/video09/2014/06/16/1989823-102-086-0009.mp4";
        String path = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4";
        mVideoView.setRender(IjkVideoView.RENDER_TEXTURE_VIEW);
        mVideoView.setVideoPath(path);
        mVideoView.start();
    }

    private void initVideoViewListener() {
        mVideoView.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(IMediaPlayer iMediaPlayer) {
                LogUtils.d("WatchVideoMonitoringActivity_log", "onPrepared: 准备完成，可以播放");
                handler.sendEmptyMessage(0);
            }
        });
        mVideoView.setOnErrorListener(new IMediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) {
                LogUtils.d("WatchVideoMonitoringActivity_log", "onError: 播放错误回调，i=" + i + ",i1=" + i1);
                return false;
            }
        });

        mVideoView.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(IMediaPlayer iMediaPlayer) {
                LogUtils.d("WatchVideoMonitoringActivity_log", "onCompletion: 播放CompletionListener回调");
            }
        });
        mVideoView.setOnInfoListener(new IMediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(IMediaPlayer iMediaPlayer, int i, int i1) {
                LogUtils.d("WatchVideoMonitoringActivity_log", "onInfo: 播放信息回调，i=" + i + ",i1=" + i1);
                return false;
            }
        });
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                switch (msg.what) {
                    case 0:

                        break;

                    case 2:

                        break;
                    case 3:

                        break;

                    default:
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


    @Override
    protected void onStop() {
        if (mVideoView.isPlaying()) {
//            stopVideo(false, false);
            mVideoView.stopPlay();
        }
        super.onStop();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        IjkMediaPlayer.native_profileEnd();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.screenshot:
                //自己申请权限了
                String audio_path = PathUtils.getInternalAppCachePath() + File.separator + "截图.png";
                final File file = new File(audio_path);
                if (!file.exists()) {
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                mVideoView.getCurrentFrame(file.getAbsolutePath());
                //这里没处理回调，保存图片是在子线程中进行，getCurrentFrame（） 的返回值 1 的作用只是已经给播放器说明要截一张图
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                        fragme.setImageBitmap(bitmap);
                    }
                }, 1000);
                break;
            case R.id.recored:
                //保存不一定是MP4格式，保存文件格式会根据文件名获取，也可以是xxx.flv等等，前提是你ffmpeg 得支持
                String video_path = PathUtils.getInternalAppCachePath() + File.separator + "ijkplayer录像.mp4";
                final File recoredFile = new File(video_path);
                if (!recoredFile.exists()) {
                    try {
                        recoredFile.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                //自己去sdcard中查看有没有文件就好,我懒（*_*）
                if (mVideoView.isRecord()) {
                    recored.setText("录制");
                    mVideoView.stopRecord();
                } else {
                    recored.setText("停止录制");
                    mVideoView.startRecord(recoredFile.getAbsolutePath());
                }
                break;
        }
    }
}